package com.sh.data.engine.web.webapi.controller.management;

import com.sh.data.engine.application.model.dto.base.PagerResponse;
import com.sh.data.engine.application.model.dto.management.UserDTO;
import com.sh.data.engine.application.model.dto.workspace.ProjectStatisticDTO;
import com.sh.data.engine.application.model.request.management.UserProjectSaveRequest;
import com.sh.data.engine.application.service.management.ProjectUserApplicationService;
import com.sh.data.engine.common.annotation.permissionCheck.PermissionCheckMethod;
import com.sh.data.engine.common.enumDefinition.ProjectStatisticTypeEnum;
import com.sh.data.engine.common.enumDefinition.RoleEnum;
import com.sh.data.engine.domain.annotation.DefaultProjectExecution;
import com.sh.data.engine.domain.annotation.LogExecution;
import com.sh.data.engine.domain.annotation.ProjectStatisticExecution;
import com.sh.data.engine.domain.annotation.userlog.Business;
import com.sh.data.engine.domain.annotation.userlog.EngineOperation;
import com.sh.data.engine.domain.base.model.UserContext;
import com.sh.data.engine.web.webapi.controller.base.response.RestResponseEntity;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Validated
@RestController
@RequestMapping("/management/user/project")
@Tag(name = "数据集成-用户工作空间管理", description = "用户工作空间管理API")
public class UserProjectController {

    //该id在不同的环境不一样
    @Value("${super.admin.id}")
    private String SUPER_ADMIN;

    @Autowired
    private ProjectUserApplicationService projectUserApplicationService;

    /**
     * 所有用户都具备创建空间的权限,创建工作空间，随即成为工作空间拥有者，roleId=2
     */
    @ProjectStatisticExecution(type = ProjectStatisticTypeEnum.REGISTER_DS)
    @RequestMapping("/addProject")
    @Operation(summary = "创建工作空间")
    @LogExecution(operation = EngineOperation.ADD, business = Business.空间)
    public RestResponseEntity<String> addProject(@RequestBody @Valid UserProjectSaveRequest param) {
        return RestResponseEntity.success(projectUserApplicationService.addProject(param));
    }

    @RequestMapping("/deleteProject")
    @Operation(summary = "删除工作空间")
    @LogExecution(operation = EngineOperation.DEL, business = Business.空间)
    public RestResponseEntity<String> deleteProject(@RequestParam Long projectId) {
        return RestResponseEntity.success(projectUserApplicationService.deleteProject(projectId));
    }

    @GetMapping("/getProjectList")
    @Operation(summary = "分页展示加入的工作空间")
//    @LogExecution(operation = EngineOperation.SELECT, business = Business.用户空间)
    public RestResponseEntity<PagerResponse<ProjectStatisticDTO>> getProjectList(
            @Parameter(description = "当前页", schema = @Schema(defaultValue = "1"))
            @RequestParam(required = false, defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页大小", schema = @Schema(defaultValue = "10"))
            @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        var result = projectUserApplicationService.getEnrichedProjectList(pageNum, pageSize);
        return RestResponseEntity.success(result);
    }

    @GetMapping("/getProjectPrivilege")
    @Operation(summary = "获取加入的工作空间（不分页)")
    public RestResponseEntity<List<ProjectStatisticDTO>> getProjectPrivilege() {
        List<ProjectStatisticDTO> projectPrivilege = projectUserApplicationService.getProjectPrivilege();
        return RestResponseEntity.success(projectPrivilege);
    }

//    /**
//     * 查看空间详情
//     * ServletUtils.getProjectId()
//     *
//     * @param projectId
//     * @return
//     */
//    @GetMapping("/getStorageInfo")
//    @Operation(summary = "根据工作空间id获取存储资源信息")
//    public RestResponseEntity<StorageDTO> getStorageInfo(@RequestParam Long projectId) {
//        return RestResponseEntity.success(projectUserApplicationService.getStorageInfo(projectId));
//    }

    /**
     * 空间管理只有1L和2L具备权限，如下四个功能需要校验角色
     *
     * @return
     */
    @GetMapping("/getProjectUser")
    @Operation(summary = "(1L or 2L or 3L)分页获取工作空间用户")
//    @LogExecution(operation = EngineOperation.SELECT, business = Business.用户空间)
    @PermissionCheckMethod(roles = {RoleEnum.SUPER_ADMIN, RoleEnum.PROJECT_OWNER, RoleEnum.PROJECT_ADMIN})
    public RestResponseEntity<PagerResponse<UserDTO>> getProjectUser(@RequestParam Integer pageNum, @RequestParam Integer pageSize) {
        PagerResponse<UserDTO> projectUser = projectUserApplicationService.getProjectUser(pageNum, pageSize);
        return RestResponseEntity.success(projectUser);
    }

    @PostMapping("/addProjectUser")
    @Operation(summary = "(1L or 2L or 3L)添加工作空间用户")
    @ProjectStatisticExecution(type = ProjectStatisticTypeEnum.USER)
    @LogExecution(operation = EngineOperation.ADD, business = Business.用户空间)
    @PermissionCheckMethod(roles = {RoleEnum.SUPER_ADMIN, RoleEnum.PROJECT_OWNER, RoleEnum.PROJECT_ADMIN})
    public RestResponseEntity<Integer> addProjectUser(@RequestParam int roleId, @RequestParam String userName) {
        return RestResponseEntity.success(projectUserApplicationService.addProjectUser(roleId, userName));
    }

//    @GetMapping("/queryProjectUser/{userId}")
//    @LogExecution(operation = com.sh.data.engine.domain.annotation.userlog.Operation.SELECT, business = Business.用户空间)
//    public RestResponseEntity<UserDTO> queryProjectUser(@PathVariable("userId") String userId) {
//        return RestResponseEntity.success(projectUserApplicationService.getUser(userId));
//    }

    @PostMapping("/deleteProjectUser")
    @Operation(summary = "((1L or 2L or 3L))删除工作空间用户")
    @LogExecution(operation = EngineOperation.DEL, business = Business.用户空间)
    @PermissionCheckMethod(roles = {RoleEnum.SUPER_ADMIN, RoleEnum.PROJECT_OWNER, RoleEnum.PROJECT_ADMIN})
    @ProjectStatisticExecution(type = ProjectStatisticTypeEnum.USER)
    public RestResponseEntity<Integer> deleteProjectUser(@RequestParam String userName) {
        return RestResponseEntity.success(projectUserApplicationService.deleteProjectUser(userName));
    }


    @PostMapping("/updateProjectUser")
    @Operation(summary = "(1L or 2L or 3L)更新工作空间用户")
    @LogExecution(operation = EngineOperation.UPDATE, business = Business.用户空间)
    @PermissionCheckMethod(roles = {RoleEnum.SUPER_ADMIN, RoleEnum.PROJECT_OWNER, RoleEnum.PROJECT_ADMIN})
    public RestResponseEntity<Integer> updateProjectUser(@RequestParam String userName, @RequestParam int roleId) {
        return RestResponseEntity.success(projectUserApplicationService.updateProjectUser(userName, roleId));
    }

    /**
     * 当前登录个人信息
     *
     * @return
     */
    @DefaultProjectExecution(description = "默认空间登陆授权")
    @RequestMapping("/getCurrentUserInfo")
    @LogExecution(operation = EngineOperation.LOGIN, business = Business.登录)
    public RestResponseEntity<UserDTO> getCurrentUserInfo() {
        if (UserContext.getUserId() == null) {
            return RestResponseEntity.error("get current user fail");
        }
        return RestResponseEntity.success(projectUserApplicationService.getUser(UserContext.getUserId()));
    }

    /**
     * (全局)用户管理
     *
     * @return
     */
    @PermissionCheckMethod(roles = {RoleEnum.SUPER_ADMIN})
    @RequestMapping("/getUserPageList")
//    @LogExecution(operation = EngineOperation.SELECT, business = Business.用户空间)
    public RestResponseEntity<PagerResponse<UserDTO>> getUserPageList(@RequestParam Integer pageNum, @RequestParam Integer pageSize) {
        //系统管理员才拥有此权限
        return RestResponseEntity.success(projectUserApplicationService.getUserPageList(pageNum, pageSize));
    }

    /**
     * (全局)提取json中的账号名
     *
     * @return
     */
    @RequestMapping("/getUserNamePageList")
    public RestResponseEntity<List<String>> getUserNamePageList() {
        return RestResponseEntity.success(projectUserApplicationService.getUserNamePageList());
    }

    /**
     * 查看用户详情
     *
     * @param userId
     * @return
     */
    @PermissionCheckMethod(roles = {RoleEnum.SUPER_ADMIN})
    @RequestMapping("/getUser/{userId}")
    public RestResponseEntity<UserDTO> getUser(@PathVariable("userId") String userId) {
        //系统管理员才拥有此权限，可以根据有效的用户id查看用户详情
        return RestResponseEntity.success(projectUserApplicationService.getUser(userId));
    }
}

